// promisify get for storage
// https://developer.chrome.com/extensions/storage#property-local
const getStorage = (key = null) => {
  return new Promise(resolve => {
    chrome.storage.local.get(key, function (data) {
      if (typeof key === 'string') {
        resolve(data[key]);
      } else {
        resolve(data);
      }
    });
  });
};

const insertJQuery = async (w = window) => {
  return new Promise(resolve => {
    const script = w.document.createElement('script');
    script.setAttribute('type', 'text/javascript');
    script.setAttribute(
      'src',
      'https://cdn.bootcss.com/jquery/3.4.1/jquery.js'
    );
    script.defer = true;
    script.onload = function () {
      // eslint-disable-next-line no-undef
      jQuery.noConflict();
      // console.log(window.jQuery)
      window.$ = window.jQuery;
      resolve();
    };
    w.document.head.appendChild(script);
  });
};

const insertMoment = (w = window) => {
  console.log(w);
  return new Promise(resolve => {
    const script = w.document.createElement('script');
    script.setAttribute('type', 'text/javascript');
    script.setAttribute(
      'src',
      'https://cdn.bootcss.com/moment.js/2.24.0/moment.min.js'
    );
    script.defer = true;
    script.onload = function () {
      resolve();
    };
    w.document.body.appendChild(script);
  });
};

const insertSimulate = (w = window) => {
  console.log(w);
  return new Promise(resolve => {
    const script = w.document.createElement('script');
    script.setAttribute('type', 'text/javascript');
    script.setAttribute(
      'src',
      'https://cdn.bootcdn.net/ajax/libs/jquery-simulate/1.0.1/jquery.simulate.js'
    );
    script.defer = true;
    script.onload = function () {
      resolve();
    };
    w.document.body.appendChild(script);
  });
};

const nextTick = (findObj, tick) => {
  function doIt() {
    let obj = findObj();
    if (!obj) {
      setTimeout(() => {
        nextTick(findObj);
      }, 200);
    }
  }
  if (tick) {
    setTimeout(doIt, tick);
  } else {
    doIt();
  }
};

const autoLoad = (time = 60000) => {
  setTimeout(() => {
    window.location.reload();
  }, time);
};
function getBase64Image(img) {
  var canvas = document.createElement('canvas');
  canvas.width = img.width;
  canvas.height = img.height;
  let ctx = canvas.getContext('2d');
  ctx.drawImage(img, 0, 0, img.width, img.height);
  let imgSrc = img.src.split('?')[0];
  let ext = imgSrc.substring(imgSrc.lastIndexOf('.') + 1).toLowerCase();
  let dataUrl = canvas.toDataURL('images/' + ext);
  console.log(dataUrl);
  return dataUrl;
}
const getBase64 = async (img) => {
  return new Promise((resolve, reject) => {
    var image = new Image();
    image.src = img;
    image.onload = function () {
      var base64 = getBase64Image(image);
      document.querySelector('#yhmwrapper').appendChild(image);
      resolve(base64);
    };
  });
};




export {
  getStorage, insertJQuery, insertMoment, nextTick, autoLoad, getBase64
};
